<script setup lang="ts">
import { ElDialog, ElMessage, ElMessageBox, ElTable } from 'element-plus'
import { ref } from 'vue'

// 分拣数据接口
interface SortingRecord {
  id: string // 分拣单号
  productId: string // 商品编号
  productName: string // 商品名称
  quantity: number // 可上架数量（原分拣数量）
  locationId: string
  expiryDate: string // 过期日期
}

// 模拟分拣数据源（用于弹窗）
const sortingRecords = ref<SortingRecord[]>([
  { id: 'SJ001', productId: 'P1001', productName: '笔记本电脑', quantity: 50, locationId: '001', expiryDate: '' },
  { id: 'SJ002', productId: 'P2002', productName: '无线鼠标', quantity: 200, locationId: '001', expiryDate: '' },
  { id: 'SJ003', productId: 'P3003', productName: '机械键盘', quantity: 80, locationId: '001', expiryDate: '' },
])

// 响应式副本，用于绑定表单数据
const sortingRecordsValue = ref([...sortingRecords.value])

interface ShelfItem {
  id: string
  productId: string
  productName: string
  price: number
  weight: number
  size: string
  quantity: number
  location: string
  locationId: string
  shelfedNum: number
  status: ShelfStatus
}

type ShelfStatus = '待上架' | '上架中' | '已上架' | '已取消'

const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(1000)

// 状态颜色映射
const statusColors: Record<ShelfStatus, 'success' | 'warning' | 'info' | 'danger'> = {
  待上架: 'info',
  上架中: 'warning',
  已上架: 'success',
  已取消: 'danger',
}

// 当前选中的行
const selectedRows = ref<ShelfItem[]>([])
const searchKeyword = ref('')

// 弹窗相关
const dialogVisible = ref(false)
const currentRow = ref<ShelfItem>()
const shelfNum = ref(0)
const selectedRecords = ref<SortingRecord[]>([])

// 初始表格数据
const tableData = ref<ShelfItem[]>([
  {
    id: 'SH001',
    productId: 'P1001',
    productName: '笔记本电脑',
    price: 6999.00,
    weight: 2.5,
    size: '35×25×3',
    quantity: 50,
    location: 'A区-货架1层',
    locationId: 'LOC-A-01',
    shelfedNum: 0,
    status: '待上架',
  },
  {
    id: 'SH002',
    productId: 'P2002',
    productName: '无线鼠标',
    price: 199.00,
    weight: 0.15,
    size: '12×6×3',
    quantity: 200,
    location: 'B区-货架3层',
    locationId: 'LOC-B-03',
    shelfedNum: 80,
    status: '上架中',
  },
  {
    id: 'SH003',
    productId: 'P3003',
    productName: '机械键盘',
    price: 899.00,
    weight: 1.2,
    size: '44×14×4',
    quantity: 80,
    location: 'C区-货架2层',
    locationId: 'LOC-C-02',
    shelfedNum: 80,
    status: '已上架',
  },
])

// 批量上架
function handleBatchShelf() {
  const validSelections = selectedRows.value.filter(item => item.status === '待上架')
  if (validSelections.length === 0) {
    ElMessage.warning('请选择待上架状态的记录')
    return
  }

  validSelections.forEach((row) => {
    row.status = '上架中'
    row.shelfedNum = 0
  })

  ElMessage.success(`已将 ${validSelections.length} 条记录设为“上架中”`)
}

// 撤回操作
async function handleRecall() {
  const validSelections = selectedRows.value.filter(item => item.status === '已上架')
  if (validSelections.length === 0) {
    ElMessage.warning('请选择已上架状态的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要撤回 ${validSelections.length} 条上架记录？`,
      '撤回确认',
      {
        confirmButtonText: '确认撤回',
        cancelButtonText: '取消',
        type: 'error',
      },
    )

    validSelections.forEach((row) => {
      row.status = '已取消'
      row.shelfedNum = 0
    })

    ElMessage.success(`已撤回 ${validSelections.length} 条上架记录`)
  }
  catch {
    ElMessage.info('已取消操作')
  }
}

// 开始/继续上架
function handleShelfOperation(row: ShelfItem) {
  currentRow.value = row
  shelfNum.value = row.status === '待上架' ? 0 : row.quantity - row.shelfedNum
  dialogVisible.value = true
}

// 确认上架
function confirmShelf() {
  if (!currentRow.value || shelfNum.value <= 0) {
    return
  }

  const row = currentRow.value!
  row.shelfedNum += shelfNum.value

  if (row.shelfedNum >= row.quantity) {
    row.status = '已上架'
    row.shelfedNum = row.quantity
  }
  else {
    row.status = '上架中'
  }

  dialogVisible.value = false
  ElMessage.success(`${row.productName} 已更新上架数量`)
}
</script>

<template>
  <div>
    <FaPageMain>
      <!-- 操作栏 -->
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <el-button type="success" style="margin-left: 12px;" @click="handleBatchShelf">
            <el-icon><Select /></el-icon>
            <span class="ml-1">批量上架</span>
          </el-button>

          <el-button type="danger" style="margin-left: 12px;" @click="handleRecall">
            <el-icon><Refresh /></el-icon>
            <span class="ml-1">撤回操作</span>
          </el-button>
        </div>

        <!-- 搜索框 -->
        <div class="search-wrapper">
          <el-input v-model="searchKeyword" placeholder="搜索产品名称/ID" clearable style="width: 300px;">
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <!-- 表格 -->
      <div class="table-wrapper">
        <ElTable
          :data="tableData"
          row-key="id"
          stripe
          style="width: 100%; max-height: calc(100vh - 200px);"
          @selection-change="(val: ShelfItem[]) => selectedRows = val"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="上架单号" width="120" />
          <el-table-column prop="productId" label="产品编号" width="120" />
          <el-table-column prop="productName" label="产品名称" />

          <el-table-column prop="price" label="单价" width="100">
            <template #default="{ row }">
              ¥{{ row.price.toFixed(2) }}
            </template>
          </el-table-column>

          <el-table-column prop="weight" label="重量（kg）" width="120" />
          <el-table-column prop="size" label="尺寸（cm³）" width="100" />

          <el-table-column prop="quantity" label="应上架数量" width="120">
            <template #default="{ row }">
              {{ row.quantity }} 件
            </template>
          </el-table-column>

          <el-table-column prop="shelfedNum" label="已上架数量" width="120">
            <template #default="{ row }">
              {{ row.shelfedNum || 0 }} 件
            </template>
          </el-table-column>

          <el-table-column prop="locationId" label="库位ID" width="130" />
          <el-table-column prop="location" label="存放位置" width="160" />

          <el-table-column prop="status" label="状态" width="140">
            <template #default="{ row }">
              <el-tag :type="statusColors[row.status as ShelfStatus]" effect="dark">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" fixed="right" width="170">
            <template #default="{ row }">
              <div v-if="['待上架', '上架中'].includes(row.status)">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleShelfOperation(row)"
                >
                  {{ row.status === '待上架' ? '开始上架' : '继续上架' }}
                </el-button>
              </div>
              <span v-else class="text-gray-400">-</span>
            </template>
          </el-table-column>
        </ElTable>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper" float-right>
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </FaPageMain>

    <!-- 上架弹窗 -->
    <ElDialog v-model="dialogVisible" title="选择分拣记录" width="800px">
      <div class="p-4">
        <!-- 分拣记录表格 -->
        <ElTable
          :data="sortingRecords"
          style="width: 100%;"
          @selection-change="(val: SortingRecord[]) => selectedRecords.value = val"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="分拣单号" width="120" />
          <el-table-column prop="productId" label="商品编号" width="120" />
          <el-table-column prop="productName" label="商品名称" />
          <el-table-column prop="quantity" label="上架数量" width="120" />
          <el-table-column prop="locationId" label="库位" width="130">
            <template #default="{ $index }">
              <el-select v-model="sortingRecordsValue.value[$index].locationId" placeholder="选择库位">
                <el-option
                  v-for="location in locations"
                  :key="location.id"
                  :label="location.name"
                  :value="location.id"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="过期日期" width="100">
            <template #default="{ $index }">
              <el-date-picker
                v-model="sortingRecordsValue.value[$index].expiryDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
              />
            </template>
          </el-table-column>
        </ElTable>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmShelf">提交</el-button>
        </span>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
/* 复用原分拣页面样式 */
.flex {
  display: flex;
}

.justify-between {
  justify-content: space-between;
}

.mb-4 {
  margin-bottom: 1rem;
}

.ml-1 {
  margin-left: 0.25rem;
}

.search-wrapper {
  display: flex;
  justify-content: flex-end;
}

.table-wrapper {
  width: 100%;
  overflow-x: auto;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.pagination-wrapper {
  margin-top: 16px;
}
</style>
